const express = require('express');
const router = express.Router();
const { getList, getDetail, newBlog, updateBlog, deleteBlog } = require('../controller/blog');
const { SuccessModel, ErrorModel } = require('../model/resModel');

// 获取全部文章
router.get('/list', function(req, res, next) {
  getList().then(lists => {
    res.json(new SuccessModel(lists))
  }).catch(err => res.json(new ErrorModel(err)))
})

// 根据ID获取单个文章
router.get('/detail/:id', function(req, res, next) {
  const { id } = req.params
  getDetail(id).then(detail => {
    res.json(new SuccessModel(detail || '无对应此ID的数据'))
  }).catch(err => res.json(new ErrorModel(err)))
})

// 新建博客
router.post('/new', function(req, res, next) {
  const { body } = req
  newBlog(body).then(blog => {
    res.json(new SuccessModel(blog))
  }).catch(err => res.json(new ErrorModel(err)))
})

// 更新博客
router.put('/update/:id', function(req, res, next) {
  const { id } = req.params
  const { body } = req
  updateBlog(id, body).then(update => {
    res.json(new SuccessModel(update))
  }).catch(err => res.json(new ErrorModel(err)))
})

// 删除博客
router.delete('/delete/:id/:author', function(req, res, next) {
  const { id, author } = req.params
  deleteBlog(id, author).then(dele => {
    res.json(new SuccessModel(dele))
  }).catch(err => res.json(new ErrorModel(err)))
})

module.exports = router;